package nspel

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/kataras/golog"
	rotateLogs "github.com/lestrrat/go-file-rotatelogs"
	"time"
)

var db *gorm.DB
var ormLogger *golog.Logger

func configOrm() {
	var data = struct {
		DriveName      string `json:"driveName"`
		DataSourceName string `json:"dataSourceName"`
		MaxIdle        int    `json:"maxIdle"`
		MaxOpen        int    `json:"maxOpen"`
		Debug          bool   `json:"debug"`
		Log            bool   `json:"log"`
		LogFile        string `json:"logFile"`
	}{}
	loadConfigJson("config/orm.json", &data)
	var err error
	db, err = gorm.Open(data.DriveName, data.DataSourceName)
	if err != nil {
		panic(err)
	}
	db.DB().SetMaxIdleConns(data.MaxIdle)
	db.DB().SetMaxOpenConns(data.MaxOpen)
	if data.Debug {
		if !data.Log {
			db.LogMode(true)
		} else {
			db.LogMode(true)
			ormLog(data.LogFile)
			db.SetLogger(ormLogger)
		}
	}
}

func ormLog(logFile string) {
	ormLogger = golog.New()
	writer, err := rotateLogs.New(
		logFile+".%Y%m%d%H%M",
		rotateLogs.WithLinkName(logFile),
		rotateLogs.WithMaxAge(7*24*time.Hour),
		rotateLogs.WithRotationTime(24*time.Hour))
	if err != nil {
		panic(err)
	}
	ormLogger.SetOutput(writer)
	// ormLogger.SetLevel("debug")
}

func GetOrm() *gorm.DB {
	return db
}
